package com.gurumades.jsonform.shared.dispatch.validators;

import java.util.Map;

import com.gurumades.jsonform.shared.dispatch.FieldHelper;
import com.gurumades.jsonform.shared.dispatch.JsonHelper;


@SuppressWarnings("rawtypes")
public class TextSizeValidator implements FormItemValidator  {
	
	@Override
	public void validate(Object item, Map<String, Object> values,
			ValidatorHelper helper) {
		
		JsonHelper jshelper  = ValidatorHelper.getJsonHelper();
		Map mapItem = jshelper.wrapItem(item);
		
		String fieldID = jshelper.getString(mapItem, "id", null);
		Object val = values.get(fieldID);
		String value = (String) jshelper.wrapItem(val).get("value");
		
		int maxLenght = jshelper.getInt(mapItem, "maxLength", 100);
		int minLength = jshelper.getInt(mapItem, "minLength", -1);
		
		boolean hasErr = false;
		
		if (value == null && minLength <= 0) {
			return;
		} else if (value != null) {
			if (!(minLength <= value.length() && maxLenght >= value.length())) {
				hasErr = true;
			}
		}else {
			hasErr = true;
		}
		
		if (hasErr) {
			helper.addError(fieldID, "The length allowed for this field is between '"+minLength+"' and '"+maxLenght+"'");
		}

	}
	
	@Override
	public boolean supportType(String type) {
		return type.startsWith("text-");
	}
}
